package com.sgcc.sx.pmos.e_sx_order.activity;

import android.content.Intent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.core.LogisticsCenter;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sgcc.sx.pmos.arouter.mall.MallArouterPath;
import com.sgcc.sx.pmos.arouter.order.OrderArouterPath;
import com.sgcc.sx.pmos.common.base.MvpBaseRecycleActivity;
import com.sgcc.sx.pmos.common.bean.BaseResponse;
import com.sgcc.sx.pmos.common.bean.PowDetileByChartBean;
import com.sgcc.sx.pmos.common.bean.PowMonthCoye;
import com.sgcc.sx.pmos.common.dialog.CommonDialog;
import com.sgcc.sx.pmos.common.utils.ArguConstant;
import com.sgcc.sx.pmos.common.utils.BigDecimalUtils;
import com.sgcc.sx.pmos.common.utils.ReflectUtils;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.sx.pmos.e_sx_order.adapter.DaypartingEleChangesAdapter;
import com.sgcc.sx.pmos.e_sx_order.bean.EnergyByMonthDetailBean;
import com.sgcc.sx.pmos.e_sx_order.bean.KeyValueBean;
import com.sgcc.sx.pmos.e_sx_order.bean.PeriodPointBean;
import com.sgcc.sx.pmos.e_sx_order.contract.DaypartingEleChangesContract;
import com.sgcc.sx.pmos.e_sx_order.presenter.DaypartingEleChangesPresenter;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 电量变更--分时段
 */
@Route(path = OrderArouterPath.ORDER_DAYPARTINGELECHANGES)
public class DaypartingEleChangesActivity extends MvpBaseRecycleActivity<KeyValueBean, DaypartingEleChangesPresenter> implements DaypartingEleChangesContract.View {
    public static int CHARTSELECT = 0x123;
    public static int CHARTSELECT_SUCCSS = 2;
    private static final String TAG = "DaypartingEleChangesAct";
    private RelativeLayout mRlSubmit;
    private String mRelationId, mPackageId, mMonth;
    private TextView tvTotal;
    private List<String> oldList;

    @Override
    protected DaypartingEleChangesPresenter createPresenter() {
        return new DaypartingEleChangesPresenter();
    }

    @Override
    protected void receiveIntentExtras() {
        super.receiveIntentExtras();
        mRelationId = getIntent().getStringExtra(ArguConstant.RELATIONID);
        mPackageId = getIntent().getStringExtra(ArguConstant.PACKAGEID);
        mMonth = getIntent().getStringExtra(ArguConstant.MONTH);
    }

    @Override
    public String getTitleText() {
        return "电量变更";
    }

    @Override
    protected void initViews() {
        super.initViews();
        title_bar.setRightIcon(R.mipmap.go_main, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goMainActivity();
            }
        });

        refreshLayout.setEnablePureScrollMode(true);
    }

    @Override
    public DaypartingEleChangesAdapter getAdapter() {
        DaypartingEleChangesAdapter daypartingEleChangesAdapter = new DaypartingEleChangesAdapter();
        daypartingEleChangesAdapter.setOnEditCallBack(new DaypartingEleChangesAdapter.OnEditCallBack() {
            @Override
            public void onCurve(int position) {
                List<KeyValueBean> data = daypartingEleChangesAdapter.getData();
                double total = 0;
                for (KeyValueBean keyValueBean : data) {
                    total += Double.parseDouble(keyValueBean.getValue());
                }
                tvTotal.setText(BigDecimalUtils.onKeep2Decimal_new(total + ""));
//                if (recycleview.getScrollState() != 0) {
//                    return;
//                }
//                daypartingEleChangesAdapter.notifyItemChanged(position);
            }

        });

        return daypartingEleChangesAdapter;
    }

    private List<String> getFieldValue(Object o) {
        try {
            List<String> list = new ArrayList<>();
            String getter = "get" + "Energy";
            for (int i = 1; i < 25; i++) {
                String s1 = getter + String.valueOf(i);
                Method method = o.getClass().getMethod(s1, new Class[]{});
                Object value = method.invoke(o, new Object[]{});
                list.add((String) value);
            }
            return list;
        } catch (Exception e) {

        }
        return null;
    }

    @Override
    public void getDataRequest(int listSize, boolean isloading) {
        super.getDataRequest(listSize, isloading);
        mPresenter.getEnergyByMonthDetail(mRelationId, mPackageId);
    }


    @Override
    public View getHeaderLayout(RelativeLayout parent) {
        View head_view = getLayoutInflater().inflate(R.layout.header_daypartingelechanges_layout, parent, false);
        tvTotal = head_view.findViewById(R.id.tvTotal);
        head_view.findViewById(R.id.llTotal).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Postcard postcard = ARouter.getInstance()
                        .build(MallArouterPath.MALL_POWSETCHART);
                String monthDate = mPeriodPointBean.getMonthDate();
                int m = Integer.parseInt(mMonth);
                postcard.withInt("startMonth", m);
                postcard.withInt("endMonth", m);
                postcard.withString("year", monthDate.substring(0, 4));
                startForActivityResult(postcard, CHARTSELECT);
            }
        });
        return head_view;
    }

    @Override
    public View getFooterLayout(RelativeLayout parent) {
        View footer_view = getLayoutInflater().inflate(R.layout.footer_daypartingelechanges_layout, parent, false);
        findFooterViewByIds(footer_view);
        return footer_view;
    }

    private void findFooterViewByIds(View footer_view) {
        mRlSubmit = (RelativeLayout) footer_view.findViewById(R.id.rl_submit);
        mRlSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<KeyValueBean> list = adapter.getData();

                PeriodPointBean periodPointBean = new PeriodPointBean();
                for (int i = 0; i < list.size(); i++) {
                    ReflectUtils.invokeSet(periodPointBean, "energy" + (i + 1), list.get(i).getValue());
                }
                periodPointBean.set_t(System.currentTimeMillis() + "");
                periodPointBean.setPeType(mPeriodPointBean.getPeType());
                periodPointBean.setPackageId(mPeriodPointBean.getPackageId());
                periodPointBean.setMonthDate(mPeriodPointBean.getMonthDate());
                periodPointBean.setRelationId(mRelationId);
                periodPointBean.setSchemeRatio1(mPeriodPointBean.getSchemeRatio1());
                periodPointBean.setSchemeRatio2(mPeriodPointBean.getSchemeRatio2());
                periodPointBean.setEnergy0("");

                String json = GsonUtils.toJson(periodPointBean);
                showPromptDialog(json);
            }
        });
    }

    private void showPromptDialog(String json) {
        CommonDialog dialog = new CommonDialog(mContext);
        dialog.setTitle("提示");
        dialog.setMessage("确认要提交" + mMonth + "月电量变更申请吗？");
        dialog.setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                dialog.dismiss();

                ARouter.getInstance()
                        .build(OrderArouterPath.ORDER_CONFIRMORDER)
                        .withString("json", json)
                        .withString("mRelationId", mRelationId)
                        .withString("monthDate", mPeriodPointBean.getMonthDate())
                        .withInt("pageFlag", 4)
                        .withBoolean("isDayparting", true)
                        .navigation();


            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();
            }
        }).show();
    }


    @Override
    public void powerChange(BaseResponse response) {
        ToastUtils.showShort(response.getMsg());
        finish();
    }

    private PeriodPointBean mPeriodPointBean;

    @Override
    public void getEnergyByMonthDetail(EnergyByMonthDetailBean response) {
        if (response.getData() != null) {
            if (!response.getCode().isEmpty()) {
                mPeriodPointBean = response.getData().get(0);
                oldList = getFieldValue(response.getData().get(0));

                double total = 0;
                List<KeyValueBean> list = new ArrayList<>();
                for (int i = 0; i < oldList.size(); i++) {
                    KeyValueBean bean = new KeyValueBean();
                    bean.setKey((i + 1) + "");
                    bean.setShowOldValue(false);
                    bean.setValue(oldList.get(i));
                    bean.setOldValue(oldList.get(i));
                    total += Double.parseDouble(oldList.get(i));
                    list.add(bean);
                }
                tvTotal.setText(BigDecimalUtils.onKeep3Decimal(total + ""));
                loadSuccess(false, list);
            }
        }
    }

    public void startForActivityResult(Postcard postcard, int requestCode) {
        LogisticsCenter.completion(postcard);
        Intent intent = new Intent(this, postcard.getDestination());
        intent.putExtras(postcard.getExtras());
        startActivityForResult(intent, requestCode);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CHARTSELECT) {
            if (resultCode == CHARTSELECT_SUCCSS) {
                PowDetileByChartBean powDetileByChartBean = (PowDetileByChartBean) data.getSerializableExtra("monthList");
                List<PowMonthCoye> month = powDetileByChartBean.getList();
                List<String> list_old = getFieldValue1(month.get(0).getPowMonth());

                double total = 0;
                List<KeyValueBean> list = new ArrayList<>();
                for (int i = 0; i < list_old.size(); i++) {
                    KeyValueBean bean = new KeyValueBean();
                    bean.setKey((i + 1) + "");
                    bean.setValue(list_old.get(i));
                    if (null != oldList && oldList.size() > 0)
                        bean.setOldValue(oldList.get(i));
                    bean.setShowOldValue(true);
                    total += Double.parseDouble(list_old.get(i));
                    list.add(bean);
                }
                tvTotal.setText(BigDecimalUtils.onKeep3Decimal(total + ""));
                loadSuccess(false, list);


            }
        }
    }


    private List<String> getFieldValue1(Object o) {
        try {
            List<String> list = new ArrayList<>();
            String getter = "get" + "REnergy";

            for (int i = 1; i < 25; i++) {
                String s1 = getter + String.valueOf(i);
                Method method = o.getClass().getMethod(s1, new Class[]{});
                Object value = method.invoke(o, new Object[]{});
                list.add((String) value);
            }
            return list;
        } catch (Exception e) {

        }
        return null;
    }

}
